// 定义一个火山引擎语音合成函数，用于发送HTTP请求
let plugin = requirePlugin('WechatSI');
let innerAudioContext: any //语音实例

let appid = "8220100142";
let access_token = "1mNlmLD3UwUs-1xEePVtgSnwhYWJhbUQ";
let cluster = "volcano_tts";

// let voice_type = "BV001_streaming";
let host = "openspeech.bytedance.com";
let api_url = `https://${host}/api/v1/tts`;

let header = { "Authorization": `Bearer;${access_token}` };

//暂停音频
export const Pause = () => {
  console.log('语音暂停了')
  innerAudioContext.pause()
}
//播放音频
export const Play = () => {
  // console.log('语音播放了')
  innerAudioContext.play()
}
// 清空语音
export const Empty = () => {
  innerAudioContext.stop(); //停止音频播放
  innerAudioContext.src = ""; //清空音频数据
}

/**
 * @param text 语音对象，传入{text:文本,voice_type:音色}
 * @param novoice 是否进行语音播放
 */
export const Voice = (text: any, novoice: boolean) => {
  const maxRetryCount = 3; // 设置最大重试次数
  let retryCount = 0; // 当前重试次数
  wx.request({
    url: api_url,
    method: 'POST',
    data: request_json(text),
    header: header,
    success: (res: any) => {
      // console.log('获取到音频了',text,novoice, res.data);
      if ('data' in res.data) {
        // 创建新的音频实例
        innerAudioContext = wx.createInnerAudioContext();

        let data = res.data['data'];
        // 解码音频数据
        let audioData = wx.base64ToArrayBuffer(data);

        // 生成唯一的文件名
        let reqid = request_json(text).request.reqid;

        // 保存文件
        wx.getFileSystemManager().writeFile({
          // filePath: wx.env.USER_DATA_PATH + '/audio.mp3',
          filePath: wx.env.USER_DATA_PATH + `/audio_${reqid}.mp3`,
          data: audioData,
          encoding: 'binary',
          success: ()=>{
            let filePath = wx.env.USER_DATA_PATH + `/audio_${reqid}.mp3`
            innerAudioContext.src = filePath;
            novoice ? Play() : Pause()
          }
        });

        // let filePath = wx.env.USER_DATA_PATH + `/audio_${reqid}.mp3`
        // innerAudioContext.src = filePath;
        // novoice ? innerAudioContext.play() : innerAudioContext.pause()
        // novoice ? Play() : Pause()
      }
    },
    fail: function () {
      if (retryCount < maxRetryCount) {
        retryCount++;
        const retryDelay = 1000; // 设置重试延迟时间为1秒
        setTimeout(() => {
        }, retryDelay); // 延迟一段时间后进行重试
      } else {
        console.log('请求失败');
        // 进行相应的处理，例如给用户提示或放弃重试
      }
    }
  });
}


const request_json = (configuration: any) => {
  return {
    "app": {
      "appid": appid,
      "token": "access_token",
      "cluster": cluster
    },
    "user": {
      "uid": "388808087185088"
    },
    "audio": {
      "voice_type": configuration.voice_type,
      // "voice_type": "BV700_streaming",
      "encoding": "mp3",
      "speed_ratio": 1.0,
      "volume_ratio": 1.0,
      "pitch_ratio": 1.0,
    },
    "request": {
      "reqid": Math.random().toString(36).substr(2, 10),
      "text": configuration.text,
      // "text": "你能合成深渊语音",
      "text_type": "plain",
      "operation": "query",
      "with_frontend": 1,
      "frontend_type": "unitTson"
    }
  };
}

